import * as express from "express";
import * as path from "path";
import * as favicon from "serve-favicon";
import * as morgan from "morgan";
import * as cookieParser from "cookie-parser";
import * as bodyParser from "body-parser";
import * as mongoose from "mongoose";
import * as helmet from "helmet";
import * as fs from "fs";
// import * as session from "express-session";
// import * as connectMongo from "connect-mongo";
import logger from "./util/logger";
import routers from "./routes";
import CONFIG from "./config";

const app = express();

logger.info("app开始启动...");
logger.info("当前环境", process.env.NODE_ENV);
logger.info("当前端口", process.env.PORT);

process.on('uncaughtException', function (err) {
    logger.error('Caught exception: ' + err.stack);
});

process.on('exit', function (code) {
    logger.warn('About to exit with code:', code);
});

// Use native promises
(<any>mongoose).Promise = global.Promise; // fuck!!!
mongoose.connect(`mongodb://${CONFIG.DATABASE.URI}`, CONFIG.DATABASE.OPTION)
    .then(() => {
        logger.info(`======================================================`);
        logger.info(`数据库连接成功`);
        logger.info(CONFIG.DATABASE.URI);
        logger.info(`======================================================`);
    })
    .catch(error => console.log(error));

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

// safety
app.use(helmet());

// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, '../client/dist')));// 暂时关闭客户端

// ensure UPLOAD_DEST is exist
const UPLOAD_DEST = CONFIG.UPLOAD_DIR;
fs.existsSync(UPLOAD_DEST) || fs.mkdirSync(UPLOAD_DEST);

// LOGGER
app.use(morgan('combined', {
    skip: (req, res) => req.url === "/_jiankong.jsp",// 目前生产环境服务器会不停的发送这个请求
    stream: logger.stream
}));

// Parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieParser());

// const MongoStore = connectMongo(session);
// app.use(session({
//     name: 'sid',
//     secret: CONFIG.SESSION_SECRET,
//     store: new MongoStore({
//         mongooseConnection: mongoose.connection
//     }),
//     resave: false,
//     saveUninitialized: true,
//     cookie: {
//         secure: false,
//         maxAge: 2 * 60 * 1000
//     }
// }));

// 路由
app.use(routers);

// catch 404 and forward to error handler
app.use((req, res, next) => {
    const err = new Error('Not Found');
    err['status'] = 404;
    next(err);
});

// error handler
app.use((err, req, res, next) => {
    // 渲染错误页面
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};
    res.status(err.status || 500);
    res.render('error');
});

module.exports = app;
